package com.gator.mybatis.result;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Authror PABLO
 * @Date 2022/4/26 23:47
 * @Desc 结果集处理
 */
public class ResultHandler {
    public <T> T handle(ResultSet resultSet, Class type) {
        Object entity = null;
        try {
            //创建对象实例
            entity = type.newInstance();
            if (resultSet.next()) {
                //将该类的所有属性取出
                for (Field field : entity.getClass().getDeclaredFields()
                ) {
                    setValue(entity, field, resultSet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) entity;
    }

    private void setValue(Object pojo, Field field, ResultSet rs) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, SQLException {
        Method setMethod = pojo.getClass().getMethod("set" + firstWordCapital(field.getName()), field.getType());
        setMethod.invoke(pojo, getResult(rs, field));
    }



    private Object getResult(ResultSet resultSet, Field field) throws SQLException {
        Class type = field.getType();
        String dataName = HumpToUnderLine(field.getName());
        if (Integer.class == type) {
            return resultSet.getInt(dataName);
        } else if (String.class == type) {
            return resultSet.getString(dataName);
        } else if (Long.class == type) {
            return resultSet.getLong(dataName);
        } else if (Boolean.class == type) {
            return resultSet.getBoolean(dataName);
        } else if (Double.class == type) {
            return resultSet.getDouble(dataName);
        } else {
            return resultSet.getString(dataName);
        }
    }


    //数据库下划线命名转为驼峰
    private String HumpToUnderLine(String para) {
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;
        if (!para.contains("_")) {
            for (int i = 0; i < para.length(); i++) {
                if (Character.isUpperCase(para.charAt(i))) {
                    sb.insert(i + temp, "_");
                    temp += 1;
                }
            }
        }
        return sb.toString().toUpperCase();
    }
    private String firstWordCapital(String word){
        String first = word.substring(0,1);
        String tail = word.substring(1);
        return first.toUpperCase() + tail;
    }
}
